package ui.activity.mine;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.jakewharton.rxbinding.view.RxView;

import net.ck.hzq.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Bean.FindAddressBean;
import base.BaseAct;
import butterknife.BindView;
import cn.finalteam.loadingviewfinal.HeaderAndFooterRecyclerViewAdapter;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.RecyclerViewFinal;
import event.AddAddressEvent;
import event.AddressEvent;
import event.DefaultAddressEvent;
import event.DeleteAddressEvent;
import event.NetErrorEvent;
import ui.activity.mine.biz.ManagerAddressBiz;
import ui.activity.mine.component.DaggerManagerAddressComponent;
import ui.activity.mine.contract.ManagerAddressContract;
import ui.activity.mine.module.ManagerAddressModule;
import ui.activity.mine.presenter.ManagerAddressPresenter;
import ui.adapter.ManagerAddressAdapter;
import util.AlertUtils;
import widget.alertview.AlertView;


/**
 * 获取地址列表
 * Created by chenjian on 2017/8/4.
 */

public class ManagerAddressAct extends BaseAct implements ManagerAddressContract.View {


    @Inject
    ManagerAddressPresenter presenter;
    @Inject
    ManagerAddressBiz biz;

    @BindView(R.id.pull_refresh_rv)
    RecyclerViewFinal rv;
    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;
    Button add;
    View footerView;

    private SharedPreferences sp;

    ManagerAddressAdapter adp;

    @Override
    protected void setRoot() {
//        setTitleBar(R.color.colorBlue);
        setContentView(R.layout.activity_manager_address);
    }

    @Override
    protected void setup() {
        DaggerManagerAddressComponent.builder().managerAddressModule(new ManagerAddressModule(this)).build().inject(this);
        setToolBar(getResources().getString(R.string.lang_manager_address), "");
        presenter.setBiz(biz);
    }


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
        footerView = View.inflate(this, R.layout.footer_manager_address, null);
        add = footerView.findViewById(R.id.manageraddress_submission);
        rv.setLayoutManager(new LinearLayoutManager(ManagerAddressAct.this));
        rv.setItemAnimator(new DefaultItemAnimator());
        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);
        rv.setOnLoadMoreListener(() -> {
        });
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                presenter.getAddressList(true, sp.getString("id", "0"));
            }
        });
        RxView.clicks(add)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> startAct(NewAddressAct.class, null));
        rv.setOnItemClickListener(new HeaderAndFooterRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder holder, int position) {
                EventBus.getDefault().post(new AddressEvent(adp.getData().get(position)));
                finish();
            }
        });
        ptr.autoRefresh(true);
    }

    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }


    @Override
    public void upDateUI(List<FindAddressBean.DataBean.ItemsBean> bean) {
        if (adp == null) {
            adp = new ManagerAddressAdapter(ManagerAddressAct.this, bean);
            adp.addFooterView(footerView);
            rv.setAdapter(adp);
        } else {
            adp.notifyDataSetChanged();
        }
    }

    @Override
    public void refreshComplete() {
        ptr.onRefreshComplete();
    }

    @Override
    public void loadMoreComplete() {
        rv.onLoadMoreComplete();
    }

    @Override
    public void hasLoadMore(boolean b) {
        rv.setHasLoadMore(b);
    }

    /**
     * 删除卡
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerDeleteAddress(DeleteAddressEvent event) {
        AlertView checkAlert = AlertUtils.showInfo(ManagerAddressAct.this, new AlertUtils.AlertViewControl() {
            @Override
            public void onItemClickListener(int positions) {
                if (positions == 0) {
                    presenter.deleteAddress(event.getAddressId(), event.getPosition());
                }
            }
        }, "提示", "是否删除此地址？");
        checkAlert.show();
    }

    /**
     * 设置默认地址
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerDefaultAddress(DefaultAddressEvent event) {
        presenter.defaultAddress(sp.getString("id", "0"), event.getAddressId(), event.getPosition());
    }

    /**
     * 新增或者修改地址刷新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void AddAddress(AddAddressEvent event) {
        presenter.getAddressList(true, sp.getString("id", "0"));
    }

}
